#!/usr/bin/perl
#creating.cgi

require './tgtman-lib.pl';
&ReadParse();
&error_setup($text{'error_mesg'});
$ipaddr=$in{'ipaddr'};
$ipaddr2=$in{'ipaddr2'};
my $ip;
my $ne;
my $type = $in{'ruletype'};
my $tgtname = $in{'tgtname'};

#check before adding rule

if(!$in{'amark'}){
	&check_ipaddress($in{'ipaddr'}) || &error($text{'err_ip'});
	$ip = $ipaddr;
}
else{
	$ip = "ALL";
}



if($in{'ipaddr2'}) {
	&check_ipaddress($in{'ipaddr2'}) || &error($text{'err_mask'});
	$ip = $ipaddr."/".$ipaddr2;
}



$err_msg = $in{'ipaddr'}."|".$in{'ipaddr2'}."|".$tgtname."|".$type;
#&error($err_msg);

my ($tgtline, @allowfile, @denyfile,@tgtips, @newfile, $newipstr, $newtgtline);
#add code of adding rule here: chenmo
if($type =~ /ALLOW/) {
	open(AL, "/etc/initiators.allow");
	@allowfile=<AL>;
	close(AL);
	$find = 0;
	foreach (@allowfile){
		$_ =~ s/\r|\n//g;
		if($_ =~ /^$tgtname\s+(\S+)$/){
			$find = 1;
			$tgtline = $_;
			@tgtips = split(/,/,$1);
			$exist_mark=0;
			foreach(@tgtips){
				if($_ =~ /^$ip$/) {
					$exist_mark=1;
				}
			}
			if(!$exist_mark){
#				if($ip eq "ALL"){
#					@tgtips=();
#				}
				push(@tgtips, $ip);
			}
			$newipstr = join(",", @tgtips);
			$newtgtline = $tgtname." ".$newipstr;
			push(@newfile, $newtgtline);
		}
		else{
			push(@newfile, $_);
		}
	}
	if(!$find){
		$newtgtline = $tgtname." ".$ip;
		push(@newfile, $newtgtline);
	}
	open(AL, ">/etc/initiators.allow");
	foreach(@newfile) {
		$newline = $_."\n";
		print AL $newline;
	}
	close(AL)
}
elsif($type =~ /DENY/) {
	open(DN, "/etc/initiators.deny");
	@denyfile=<DN>;
	close(DN);
	$find = 0;
	foreach (@denyfile){

		$_ =~ s/\r|\n//g;
		if($_ =~ /^$tgtname\s+(\S+)$/){
			$find = 1;
			$tgtline = $_;
			@tgtips = split(/,/,$1);

			$exist_mark=0;
			foreach(@tgtips){
				if($_ =~ /^$ip$/) {
					$exist_mark=1;
				}
			}
			if(!$exist_mark){
#				if($ip eq "ALL"){
#					@tgtips=();
#				}				
				push(@tgtips, $ip);
			}
			
			#push(@tgtips, $ip);
			$newipstr = join(",", @tgtips);
			$newtgtline = $tgtname." ".$newipstr;
			push(@newfile, $newtgtline);
		}
		else{
			push(@newfile, $_);
		}
	}
	if(!$find){
		$newtgtline = $tgtname." ".$ip;
		push(@newfile, $newtgtline);
	}
	open(DN, ">/etc/initiators.deny");
	foreach(@newfile) {
		$newline = $_."\n";
		print DN $newline;
	}
	close(DN)	
}
else{
	# do nothing
}
#-----------------------------------------
system("/etc/init.d/iscsi-target restart");
&redirect("target_iprule.cgi?tgtname=$tgtname"); 